
#include "SmartStaticMeshExtensions.h"

TArray<FString> USmartStaticMeshExtensions::SmGetMaterialSlotNames(UStaticMesh * StaticMesh)
{
	TArray<FString> SlotNames;
	//TArray<FStaticMaterial> StaticMaterials = staticMesh->StaticMaterials;
	TArray<FStaticMaterial> StaticMaterials = StaticMesh->GetStaticMaterials();
	for (FStaticMaterial StaticMaterial : StaticMaterials) {
		SlotNames.Add(StaticMaterial.MaterialSlotName.ToString());
	}
	return SlotNames;
}

void USmartStaticMeshExtensions::SmClearEmptyMaterials(UStaticMesh * StaticMesh)
{
	TArray<FName> MaterialSlotNames;
	TArray<FStaticMaterial> StaticMaterials02 = StaticMesh->GetStaticMaterials();
	TArray<FStaticMaterial> StaticMaterials = StaticMesh->GetStaticMaterials();
	FMeshSectionInfoMap SectionInfoMap = StaticMesh->GetSectionInfoMap();

	for (TPair<uint32, FMeshSectionInfo> PairInfo : SectionInfoMap.Map) {
		FMeshSectionInfo Info = PairInfo.Value;
		MaterialSlotNames.Add(StaticMaterials[Info.MaterialIndex].MaterialSlotName);
	}
	TArray<FStaticMaterial> RemoveMaterials;
	for (FStaticMaterial Material : StaticMaterials) {
		if (!MaterialSlotNames.Contains(Material.MaterialSlotName)) {
			RemoveMaterials.Add(Material);
		}
	}
	for (FStaticMaterial Material : RemoveMaterials) {
		StaticMaterials.Remove(Material);
	}

	//staticMesh->StaticMaterials = StaticMaterials;
	StaticMesh->SetStaticMaterials(StaticMaterials);
	TMap<uint32, FMeshSectionInfo> ResultSectionInfoMap;
	for (TPair<uint32, FMeshSectionInfo> PairInfo : SectionInfoMap.Map) {
		FMeshSectionInfo Info = PairInfo.Value;
		int32 Index;
		if (StaticMaterials.Find(StaticMaterials02[Info.MaterialIndex], Index))
		 {
			Info.MaterialIndex = Index;
			ResultSectionInfoMap.Add(PairInfo.Key, Info);
		}
	}
	StaticMesh->GetSectionInfoMap().Map = ResultSectionInfoMap;
	StaticMesh->FixLODRequiresAdjacencyInformation(0);
	for (int32 n = 0; n < StaticMaterials.Num();n++) {
		StaticMesh->SetMaterial(n, StaticMaterials[n].MaterialInterface);
	}
}
